﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;

namespace UIFramework
{
    /// <summary>
    /// 存放GameObject，便于在使用某个时直接读取即可
    /// </summary>
    public class UINameTable : MonoBehaviour
    {
        /// <summary>
        /// 向外开放的字段
        /// </summary>
        public Dictionary<string, GameObject> GORefrence
        {
            get
            {
                if (_DictUIName == null)
                {
                    Init();
                }
                return _DictUIName;
            }
            private set { }
        }

        /// <summary>
        /// 实际存放数据的字典
        /// </summary>
        private Dictionary<string, GameObject> _DictUIName;

        //展示在监事面板上的数组
        [SerializeField]
        private List<GameObject> _ObjectList;

        /// <summary>
        /// 初始化数据
        /// </summary>
        private void Init()
        {

            var content = transform.Find("Content");
            var mask = transform.Find("Mask");

            //将Content节点自动添加到数据
            if (content != null)
            {
                _ObjectList.Add(content.gameObject);
            }
            //将Mask节点自动添加到数据
            if (content != null)
            {
                _ObjectList.Add(mask.gameObject);
            }

            // 字典内容
            _DictUIName = new Dictionary<string, GameObject>();

            for (int i = 0; i < _ObjectList.Count; i++)
            {
                if (!_DictUIName.ContainsKey(_ObjectList[i].name))
                {
                    _DictUIName.Add(_ObjectList[i].name, _ObjectList[i]);
                }
                else
                {
                    Debug.LogError("需要保存且被引用的对象名不同相同!" + _ObjectList[i].name);
                }
            }
        }

        /// <summary>
        /// 该游戏物体销毁时，释放引用
        /// </summary>
        private void OnDestroy()
        {
            //Debug.Log(gameObject.name + " GameObject Refrence Clear!");
            if (_DictUIName != null)
            {
                _DictUIName.Clear();
                _DictUIName = null;
            }
        }
    }
}